package com.jml.AQS;

import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class 手写Semaphore {

    private Sync sync;

    public 手写Semaphore(int count) {
        sync = new Sync(count);
    }

    private void acquire() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    private void release() {
        sync.releaseShared(1);

    }



    class Sync extends AbstractQueuedSynchronizer {
        public Sync(int count) {
            setState(count);
        }

        // acquire就是对state进行类减，当state-1小于0或者CAS修改state成功了，
        // 就不可以再减了就让这个线程进行阻塞进入AQS的双向链表阻塞队列，
        // 就不能获取许可。否则就一直循环去修改state直到成功
        @Override
        protected int tryAcquireShared(int acquires) {
            for (;; )  {
                int oldState = getState();
                int newState = oldState-acquires;
                if(newState<0||compareAndSetState(oldState,newState)){
                    return newState<0?-1:1;

                }
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        手写Semaphore semaphore = new 手写Semaphore(1);
        semaphore.acquire();
        semaphore.release();

        Semaphore semaphore1 = new Semaphore(1);
        semaphore1.acquire();
        semaphore1.release();
    }


}
